import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MyZipCompressing {
	
	public static void main(String[] args) throws IOException{
		
		File file = new File("G:\\code\\分支");
		File[] files = file.listFiles();
		for(File f : files){
			if(f.isDirectory()){
				MyZipCompressing myZip = new MyZipCompressing();
				myZip.zip("G:\\code\\分支\\"+f.getName()+".zip",f);
			}
		}
	}
	
	private void zip(String zipFileName,File inputFile) throws IOException{
		
		System.out.println("压缩中...");
		
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
		
		zip(out,inputFile,inputFile.getName());

		out.close();
	}
	
	private void zip(ZipOutputStream out,File f,String base) throws IOException{
		if(f.isDirectory()){
			File[] fl = f.listFiles();
			if(fl.length == 0){
				out.putNextEntry(new ZipEntry(base + "/"));
				System.out.println(base + "/");
			}
			
			for(int i=0;i<fl.length;i++){
				zip(out,fl[i],base+"/"+fl[i].getName());
			}
		}else{
			out.putNextEntry(new ZipEntry(base));
			System.out.println(base);
			FileInputStream in = new FileInputStream(f);
			BufferedInputStream bi = new BufferedInputStream(in);
			
			byte[] buffer = new byte[1024];
			int length = bi.read(buffer, 0, 1024);
			
			while(length > 0){
				out.write(buffer, 0, length);
				length = bi.read(buffer, 0, 1024);
			}
			
			bi.close();
			in.close();
		}
	}
}
